package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.device.protocol.command.Frame;
import com.cloudfun.campusshare.device.protocol.command.PumpFrame;
import com.cloudfun.campusshare.entity.CommandMessageEntity;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.repo.CommandMessageRepo;
import com.cloudfun.campusshare.repo.DeviceEntityRepo;
import com.cloudfun.campusshare.service.CommandMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Huqin on 2020/2/10
 */
@Service
public class CommandMessageServiceImpl implements CommandMessageService {

    @Autowired
    private CommandMessageRepo commandMessageRepo;

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

    @Override
    public void create(String deviceType, String imei, Frame frame) {
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        if (null == deviceEntity) {
            return;
        }
        CommandMessageEntity entity = CommandMessageEntity.builder()
                .deviceType(deviceType)
                .deviceId(deviceEntity.getId())
                .content(frame.toString())
                .checksum(frame.additionalCheckSumStr())
                .build();
        commandMessageRepo.save(entity);
    }

    @Override
    public void create(String deviceType, String imei, PumpFrame frame) {
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        if (null == deviceEntity) {
            return;
        }
        CommandMessageEntity entity = CommandMessageEntity.builder()
                .deviceType(deviceType)
                .deviceId(deviceEntity.getId())
                .content(frame.toString())
                .checksum(frame.getCheckSum())
                .build();
        commandMessageRepo.save(entity);
    }

}
